package com.tourscool.springboot.starter.redisson;

import org.apache.commons.lang3.StringUtils;

/**
 * RedisKey工具
 *
 * @author Carlton
 * @date 2018/12/27
 */
public final class RedisKey {
    /**
     * Redis Key。Key的长度一定要控制
     *
     * @param projectName  项目名称
     * @param databaseName 数据库名称
     * @param tableName    表名称
     * @param key          业务Key
     * @return hp:order:order-no:13121211121212
     */
    public static String key(String projectName, String databaseName, String tableName, String key) {
        checkNull(projectName, databaseName);
        StringBuilder sb = new StringBuilder();
        sb.append(projectName).append(":").append(databaseName);
        if (StringUtils.isNotEmpty(tableName)) {
            sb.append(":").append(tableName);
        }
        if (StringUtils.isNotEmpty(key)) {
            sb.append(":").append(key);
        }
        return sb.toString();
    }

    /**
     * Redis 锁的Key
     *
     * @param projectName  项目名称
     * @param databaseName 数据库名称
     * @param tableName    表名称
     * @param key          业务Key
     * @return hp:order:order-no:lk:13121211121212
     */
    public static String lockKey(String projectName, String databaseName, String tableName, String key) {
        checkNull(projectName, databaseName);
        StringBuilder sb = new StringBuilder();
        sb.append(projectName).append(":").append(databaseName).append(":lk");
        if (StringUtils.isNotEmpty(tableName)) {
            sb.append(":").append(tableName);
        }
        if (StringUtils.isNotEmpty(key)) {
            sb.append(":").append(key);
        }
        return sb.toString();
    }

    private static void checkNull(String projectName, String databaseName) {
        assert StringUtils.isNotEmpty(projectName);
        assert StringUtils.isNotEmpty(databaseName);
    }
}
